//
//  ZGLScoreBContentController.m
//  ZeegingLottery
//
//  Created by 李曌 on 2018/11/1.
//  Copyright © 2018 蒂埃里. All rights reserved.
//

#import "ZGLScoreBContentController.h"
#import "ZGLTeamScoreCell.h"
#import "ZGLScoreListHeader.h"

static NSString *ZGLTeamScoreCellID = @"ZGLTeamScoreCell";
static NSString *ZGLScoreListGroupHeaderID = @"ZGLScoreListGroupHeaderID";
@interface ZGLScoreBContentController ()

@property (nonatomic, assign) BOOL moreGroup;

@property (nonatomic, strong) NSMutableArray *dataArray;

@property (nonatomic, strong) NSArray *sortArray;

@end

@implementation ZGLScoreBContentController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.moreGroup = self.index>6 ? YES:NO;
    
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        
        [self getScoreBoardListWithLeagueid:self.index];
    });
    
    //注册组头
    [self.tableView registerNib:[UINib nibWithNibName:@"ZGLScoreListHeader" bundle:nil] forHeaderFooterViewReuseIdentifier:ZGLScoreListGroupHeaderID];
    //h注册cell
    [self.tableView registerNib:[UINib nibWithNibName:@"ZGLTeamScoreCell" bundle:nil] forCellReuseIdentifier:ZGLTeamScoreCellID];
    
    
    //
    WS(weakself)
    MJRefreshNormalHeader *refresh = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        
        [weakSelf getScoreBoardListWithLeagueid:weakSelf.index];
        
    }];
    refresh.lastUpdatedTimeLabel.hidden = YES;
    self.tableView.mj_header = refresh;
    self.tableView.showsVerticalScrollIndicator = NO;
    
}

//- (instancetype)initWithStyle:(UITableViewStyle)style
//{
//    return [super initWithStyle:UITableViewStyleGrouped];
//}

- (NSMutableArray *)dataArray
{
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}

- (NSArray *)sortArray
{
    if (!_sortArray) {
        _sortArray = [NSArray array];
    }
    return _sortArray;
}

- (void)getScoreBoardListWithLeagueid:(NSInteger )index
{
    WS(weakself)
    [sZGLHTTPRequestManager getScoreBoardListWithLeagueid:index Success:^(id responsedata) {
        
        if (_moreGroup) {
            
            NSArray *keyArray = [responsedata allKeys];
            weakSelf.sortArray = [keyArray sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
                
                NSComparisonResult result = [obj1 compare:obj2];
                
                return result;
            }];
            DLog(@"_sortArray--%@",_sortArray);
            
            
            for (int i = 0; i<keyArray.count; i++) {
                
                NSArray *groupArray = [responsedata objectForKey:_sortArray[i]];
            
                [weakSelf.dataArray addObject:groupArray];
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    
                    [weakSelf.tableView.mj_header endRefreshing];
                    [weakSelf.tableView reloadData];
                });
            }
            
        }else{
            
            weakSelf.dataArray = [ZGLScoreBoardTeamModel mj_objectArrayWithKeyValuesArray:responsedata];
            dispatch_async(dispatch_get_main_queue(), ^{
                
                [weakSelf.tableView.mj_header endRefreshing];
                [weakSelf.tableView reloadData];
            });
        }
        
        DLog(@"dataArray.count--%ld---self.dataArray-%@",self.dataArray.count,self.dataArray);
        
        
        
    } Fail:^(ZGLRespondStatusCode bef_status, NSString *bef_message, NSError *error) {
        
    }];
    
}


#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return _moreGroup ? _dataArray.count:1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    if (_moreGroup) {
        NSArray *array = _dataArray[section];
        return array.count;
    }else{
        return _dataArray.count;
    }
    
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    NSString *CellID = [NSString stringWithFormat:@"%ldZGLTeamScoreCell%ld",indexPath.section,indexPath.row];;
    
//    ZGLTeamScoreCell *cell = [tableView dequeueReusableCellWithIdentifier:ZGLTeamScoreCellID forIndexPath:indexPath];
    ZGLTeamScoreCell *cell = [tableView dequeueReusableCellWithIdentifier:CellID];
    if (!cell) {
        cell = [ZGLTeamScoreCell teamScoreCell];
    }
    
    CGFloat cellIndex = indexPath.row;
    UIColor *cellColor = sRGBHexAlpha(0xFFF8DC, 1.0);
    if (_moreGroup) {
        NSArray *array = _dataArray[indexPath.section];
        ZGLScoreBoardTeamModel *model = [ZGLScoreBoardTeamModel mj_objectWithKeyValues:array[indexPath.row]];
        cell.model = model;
        if (cellIndex<2) {
            cell.backgroundColor = cellColor;
        }
    }else{
        cell.model = _dataArray[indexPath.row];
        
        //排名颜色
        if (_index == 1 || _index == 6) {
            
            if (cellIndex<2) {
                cell.backgroundColor = cellColor;
            }
        }else{
            
            if (cellIndex<4) {
                cell.backgroundColor = cellColor;
            }
        }
    }
    return cell;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    
    ZGLScoreListHeader *headerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:ZGLScoreListGroupHeaderID];
    
    if (_moreGroup) {
        NSString *groupStr = _sortArray[section];
        headerView.groupLabel.text = [NSString stringWithFormat:@"Group %@",groupStr];
    }else{
        [headerView.groupLabel setHidden:YES];
        headerView.teamLabelX.constant = 10;
    }
    
    //解决背景色问题
    UIView *bgColorView = [[UIView alloc]initWithFrame:headerView.bounds];
    bgColorView.backgroundColor = [UIColor whiteColor];
    headerView.backgroundView = bgColorView;
    
    return headerView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 40;
}


- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.01;
}


/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
